<?
function GetConnection()
{
	global $password;
	$dbname='plotkinm_db';
	$server='localhost';
	$port=3306; 
	$user='plotkinm';
	$password='FaceBooK';
	$conn = new mysqli($server,$user, $password, $dbname,$port);
	return $conn;
}
function GetAll()
{
	$conn = GetConnection();
	$results = $conn->query('SELECT * FROM US_Zip_Codes');
	$error=$conn->error;
	return $results;	
}

// the good stuff starts here
if ((isset($_REQUEST['_request']) && $_REQUEST['_request'] == 'extract')
 && (isset($_REQUEST['term']) && !empty($_REQUEST['term']))
 && (isset($_REQUEST['source']) && !empty($_REQUEST['source']))) // we good?
{
	$term=$_REQUEST['term'];
	$len=strlen($term);
	$results = GetAll();
	$data = array();
	while ($rs = $results->fetch_assoc()) {
		$temp=$rs[$_REQUEST['source']];
		if (strncasecmp($temp,$term,$len) == 0 // if term matches the start of the string 
		&& !in_array($temp, $data)) // ... and the string is not yet in the data array
			$data[] = $temp;	// then add it!			
	}
	echo json_encode(Array('aaData' => $data));			
	die();	
}
?>
<!doctype html>
 
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Web Course Graduate Final</title>
    <author>Joe Gentile</author>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
    <script src="http://code.jquery.com/jquery-1.8.3.js"></script>
    <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
    <script>
    $(function() {
     	$("#US_City").autocomplete({
     		source: function( request, response ) {
			            $.get("final.php",{_request: 'extract', term: request.term, source: 'city'},
			            	function(data){
			            		var myarray = new Array();
			            		myarray = data.aaData;
			            		response(myarray);
			            		return false;
			            	},'json');
			        }
		});
     	$("#US_State").autocomplete({
 		source: function( request, response ) {
		            $.get("final.php",{_request: 'extract', term: request.term, source: 'state'},
		            	function(data){
		            		var myarray = new Array();
		            		myarray = data.aaData;
		            		response(myarray);
		            		return false;
		            	},'json');
		        }
		});
	});	
    </script>
</head>
<body>
 
<div class="ui-widget">
    <label for="US_City">US Cities:</label>
    <input id="US_City" />
    <label for="US_State">US States:</label>
    <input id="US_State" />
</div>
 
</body>
</html>